package cn.itsource.order.controller;

import cn.itsource.basic.domain.aplipayCommon.AlipayConfig;
import cn.itsource.basic.domain.aplipayCommon.AlipayParams;
import cn.itsource.order.domain.OrderAdopt;
import cn.itsource.order.mapper.OrderAdoptMapper;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayReturnController {


    @Autowired
    private AlipayParams alipayInfo;

    /**
     * 同步请求
     *
     * @return
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            //把支付宝传递的参数封装为一个map集合
            Map<String, String[]> requestParams = request.getParameterMap();//{hobby:[java,c],name:"王天霸"}
            //循环迭代map
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                //获取map的key值
                String name = (String) iter.next();
                //通过key获取对应的值
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }

                params.put(name, valueStr);//{hobby:"java,c", name:"王天霸"}
            }
            //获取appid
           /* String app_id = params.get("app_id");
            //获取支付信息对象
            TPayAlipayInfo alipayInfo = alipayInfoService.loadByAppid(app_id);*/

            //验签(校验数据在传输过程中，是否被破环，如果被破坏，验签失败，如果数据没有被破环，验签成功)
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipayPublicKey(), AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            //——请在这里编写您的程序（以下代码仅作参考）——
            if (signVerified) {
                //跳转到成功界面
                return "redirect:http://localhost:8082/success.html";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "redirect:http://localhost:8082/error.html";
    }
}
